<template>
  <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="mb-5px" label-width="85px">
    <el-form-item label="文件组名称" prop="groupName">
      <ns-input
        v-model="queryParams.groupName"
        class="!w-240px"
        clearable
        placeholder="请输入文件组名称"
        @keyup.enter="handleQuery"
      />
    </el-form-item>
    <el-form-item label="文件名称" prop="fileName">
      <ns-input
        v-model="queryParams.fileName"
        class="!w-240px"
        clearable
        placeholder="请输入文件名称"
        @keyup.enter="handleQuery"
      />
    </el-form-item>

    <el-form-item>
      <el-button @click="handleQuery">
        <Icon class="mr-5px" icon="ep:search" />
        搜索
      </el-button>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh" />
        重置
      </el-button>
    </el-form-item>
  </el-form>

  <!-- <el-table
    v-loading="loading"
    ref="treeTableRef"
    :data="rightList"
    row-key="id"
    :default-expand-all="isExpandAll"
    max-height="480"
    :expand-row-keys="expandRowKeys"
  >
    <el-table-column type="selection" width="85" />
    <el-table-column :show-overflow-tooltip="true" prop="name" label="文件名称">
      <template #default="scope">
        <el-icon v-if="scope.row.type === 1"><Folder /></el-icon
        ><span style="margin-left: 5px">{{ scope.row.name }}</span>
      </template>
    </el-table-column>
  </el-table> -->
  <el-row :gutter="20">
    <el-col :span="12">
      <h3>正向样本</h3>
      <el-tree
        ref="leftTreeRef"
        style="max-width: 100%; height: 500px; overflow-y: auto"
        class="ov"
        :data="leftList"
        show-checkbox
        node-key="id"
        :default-checked-keys="leftSelected"
        :props="defaultProps"
      >
        <template #default="{ node, data }">
          <el-icon v-if="data.type === 1"><Folder /></el-icon
          ><span style="margin-left: 5px">{{ node.label }}</span>
        </template>
      </el-tree></el-col
    >
    <el-col :span="12">
      <h3>反向样本</h3>
      <el-tree
        ref="rightTreeRef"
        style="max-width: 100%; height: 500px; overflow-y: auto"
        class="ov"
        :data="rightList"
        show-checkbox
        node-key="id"
        :default-checked-keys="rightSelected"
        :props="defaultProps"
      >
        <template #default="{ node, data }">
          <el-icon v-if="data.type === 1"><Folder /></el-icon
          ><span style="margin-left: 5px">{{ node.label }}</span>
        </template>
      </el-tree></el-col
    >
  </el-row>
</template>
<script lang="ts" setup>
import { Folder } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElTable } from 'element-plus'
import { getFileTree } from '@/api/develop/file'
import { cloneDeep } from 'lodash-es'

const message = useMessage() // 消息弹窗

const isExpandAll = ref(false) // 是否展开，默认全部折叠
const Step1Ref = ref<FormInstance>()
const queryFormRef = ref<FormInstance>() // 搜索的表单
const treeTableRef = ref<InstanceType<typeof ElTable>>()
const leftTreeRef = ref()
const rightTreeRef = ref()
const loading = ref(false) // 列表的加载中
const leftList = ref([]) // 正向列表的数据
const rightList = ref([]) // 反向列表的数据
const defaultProps = {
  children: 'children',
  label: 'name'
}
const queryParams = reactive({
  groupName: '',
  fileName: ''
})

/** 打开弹窗 */
const open = () => {
  getList()
}

/** 提交表单 */
const submitForm = async () => {
  return new Promise((resolve, reject) => {
    // 获取选中的文件，并且过滤出文件（1为文件夹，2为文件）
    const leftFiles = leftTreeRef.value?.getCheckedNodes()?.filter((item) => item.type == 2)
    const rightFiles = rightTreeRef.value?.getCheckedNodes()?.filter((item) => item.type == 2)
    console.log('files', leftFiles, rightFiles)
    if ((leftFiles && leftFiles.length === 0) || (rightFiles && rightFiles.length === 0)) {
      message.warning('请选择文件')
      reject()
      return
    }
    // 发送操作成功的事件
    emit('success', leftFiles, rightFiles)
    resolve(true)
    resetForm()
  })
}

let leftSelected = []
let rightSelected = []
const setTable = (val = []) => {
  leftSelected = val
  rightSelected = val
}

defineExpose({ open, submitForm, setTable }) // 提供 open 方法，用于打开弹窗
/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 设置选中的文件
const setTableSelection = (val) => {
  val.children.forEach((item) => {
    if (item.children && item.children.length > 0) setTableSelection(item)
    if (leftSelected.includes(item.id as never)) {
      // expandRowKeys.value.push(val.id as never)
      treeTableRef.value?.toggleRowSelection(item, true)
    }
  })
}

const expandRowKeys = ref([])
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getFileTree(toRaw(queryParams))
    rightList.value = cloneDeep(data)
    leftList.value = cloneDeep(data)
    await nextTick()
    data.forEach((item) => {
      setTableSelection(item)
    })

    console.log('expandRowKeys.value', expandRowKeys.value)
  } finally {
    loading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  Step1Ref.value?.resetFields()
  queryFormRef.value?.resetFields()
}
</script>
<style lang="scss" scoped>
.form-wrap-step1 {
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
